<?php

namespace support;

class Response
{
    protected $data;
    protected $type = 'text/html';
    protected $code = 200;
    protected $header = [];

    protected $mimeType = [
        'json'  => 'application/json,text/x-json,application/jsonrequest,text/json',
        'html'  => 'text/html,application/xhtml+xml,*/*',
        'text'  => 'text/plain',
    ];

    public function __construct($data = '', $type = 'html', $code = 200)
    {
        $this->data = $data;
        $this->type = $type;
        $this->code = $code;
    }

    public function send()
    {
        http_response_code($this->code);
        $type = $this->mimeType[$this->type]  ?? 'application/json';
        header('Content-Type: ' . $type . '; charset=utf-8');
        echo $this->data;
        if (function_exists('fastcgi_finish_request')) {
            // 提高页面响应
            fastcgi_finish_request();
        }
    }

    public function create($data, string $type = 'html', $code = 200)
    {
        /** @var Response */
        $res = app(Response::class);
        return $res->send([$data, $type, $code]);
    }

    public function header($headers = [])
    {
        $this->header = array_merge($this->header, $headers);
        return $this;
    }
}
